const express = require("express");
const router = express.Router();
const axios = require('axios')
const db = require('../../db/index.js')
// const { getBalance } = require('../units/index.js')


// 获取交易数据
router.get("/get/blockchain/explorer/list", async (req, res) => {

    try {
        const address = req.query.address || '0x23f4569002a5A07f0Ecf688142eEB6bcD883eeF8'
        const page = req.query.page || 0
        const size = req.query.size || 20

        const url = `https://api.blockchain.info/v2/eth/data/account/${address}/wallet?page=${page}&size=${size}`;

        const response = await axios.get(url);
        const list = response.data.accountTransactions
        if (!Array.isArray(list) || list.length === 0) {
            return res.fail('获取交易数据为空!')
        }
        let updateSql = 'DELETE FROM record_table WHERE address = ?'
        db.query(updateSql, [address], async (err, results) => {
            if (err) return res.fail(err)
            const insertSql = 'INSERT INTO record_table SET ?'
            for (const item of list) {
                await new Promise((resolve, reject) => {
                    db.query(insertSql, { address, ...item }, (err, result) => {
                        if (err) return reject(err);
                        resolve(result);
                    });
                });
            }
            res.success({ message: '同步成功', data: response.data });

        })

    } catch (error) {
        console.error(error);
        res.fail(error)
    }
});


module.exports = router;